/**
 * Copyright(c) 2015 BASUNG Techonologies Co., Ltd.
 * <p/>
 * History:
 * 15/8/28 下午5:46 Created by leijinghan
 */
package com.jade.bss.db.impl;

import com.jade.bss.DbException;
import com.jade.bss.db.IBaseDao;
import com.jade.framework.base.criterion.Criteria;
import com.jade.framework.base.criterion.sql.SqlUtils;
import com.jade.framework.base.util.PagingList;

import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TemporalType;
import java.util.Date;

/**
 * Explain: dao层公共接口实现
 *
 * @author <a href="mailto:jinghan.lei@basung.com">leijinghan</a>
 * @date 15/8/28 下午5:46
 * @version 1.0
 */
@Named("bss_baseDao")
public class BaseDao<M extends java.io.Serializable, PK extends java.io.Serializable> implements IBaseDao<M,PK>
{
    @PersistenceContext(unitName = "default")
    private EntityManager entityManager;

    public void add(M model) throws DbException
    {
        entityManager.persist(model);
    }

    public void update(M model) throws DbException
    {
        entityManager.merge(model);
    }

    public void delete(M model) throws DbException
    {
       entityManager.remove(model);
    }

    public M get(Class<M> model, PK id)
    {
        return entityManager.find(model, id);
    }

    public PagingList<M> listall(Class<M> clazz, Criteria criteria)
    {
        String sql = "SELECT "+clazz.getSimpleName().toLowerCase()+" FROM "+clazz.getSimpleName()+" "+clazz.getSimpleName().toLowerCase()+" ";
        return SqlUtils.sqlQuery(sql, entityManager, criteria);
    }

    /**
     * 执行insert,update,delete批处理语句  未能全部实现－待定
     */
    protected int execteBulk(final String hql, final Object... paramlist) {
        Query query = entityManager.createQuery(hql);
        setParameters(query, paramlist);
        Object result = query.executeUpdate();
        return result == null ? 0 : ((Integer) result).intValue();
    }

    protected int execteNativeBulk(final String natvieSQL, final Object... paramlist) {
        Query query = entityManager.createNativeQuery(natvieSQL);
        setParameters(query, paramlist);
        Object result = query.executeUpdate();
        return result == null ? 0 : ((Integer) result).intValue();
    }

    protected void setParameters(Query query, Object[] paramlist) {
        if (paramlist != null) {
            for (int i = 0; i < paramlist.length; i++) {
                if(paramlist[i] instanceof Date) {
                    query.setParameter(i, (Date)paramlist[i], TemporalType.TIMESTAMP);
                } else {
                    query.setParameter(i, paramlist[i]);
                }
            }
        }
    }
}
